import {Component, HostListener, OnDestroy, OnInit} from "@angular/core";
import {LocalStorageService} from "../local-storage-service";
import {CommService} from "../comm-service";
import {Router} from "@angular/router";

declare var $: any;

@Component({
  template: `
    <div [style.height]="ctrroomHeightstr">
      <div class="modulgl-cotent">
        <div class="mc-header">
          <div class="mch-left">
            <div class="mch-leftimg"></div>
          </div>
          <div class="mch-right page-header navbar" style="background-color:transparent">
            <div class="top-menu" style="width: 100%">
              <ul class="nav navbar-nav pull-right">
                <li>
                  <div style="min-width: 250px">
                    <ksjh-kscc></ksjh-kscc>
                  </div>
                </li>
                <li class="dropdown dropdown-user">
                  <a href="javascript:void(0);" class="dropdown-toggle lnamec" data-toggle="dropdown"
                     data-hover="dropdown"
                     data-close-others="true">
                    <label class="lc" title="角色">
                      <i class="fa fa-address-card"></i>
                      <span class="username-hide-on-mobile lc"> {{nowrolemc}} </span>
                    </label>
                    <i class="fa fa-angle-down"></i>
                  </a>
                  <ul *ngIf="loginuserRoleList.length" class="dropdown-menu dropdown-menu-default" style="width: auto">
                    <li *ngFor="let item of loginuserRoleList">
                      <a href="javascript:void(0)" (click)="selectNowRole(item)">
                        {{item.name}}
                      </a>
                    </li>
                  </ul>
                </li>
                <li class="dropdown dropdown-user">
                  <a href="javascript:void(0);" class="dropdown-toggle lnamec" data-toggle="dropdown"
                     data-hover="dropdown"
                     data-close-others="true">
                    <label class="lc" title="用户名">
                      <span class="glyphicon glyphicon-user"></span>
                      <span class="username-hide-on-mobile lc"> {{loginusername}} </span>
                    </label>
                    <i class="fa fa-angle-down"></i>
                  </a>
                  <ul class="dropdown-menu dropdown-menu-default" style="width: auto">
                    <li>
                      <a href="javascript:void(0)" (click)="editePWD()">
                        <i class="fa fa-pencil-square-o"></i> 修改密码
                      </a>
                    </li>
                    <li>
                      <a href="javascript:void(0)" (click)="toLogin()">
                        <i class="fa  fa-sign-out"></i> 退出
                      </a>
                    </li>
                  </ul>
                </li>
              </ul>
            </div>
          </div>
        </div>

        <div class="mc-middle">
          <div class="title"></div>
          <div class="module" *ngIf="allModules.length">
            <div *ngFor="let item of allModules" class="module_item" (click)="gotoModule(item)">
              <div class="module_item_inner">
                <div class="icon">
                  <div [class]="item.iconclass"></div>
                </div>
                <div class="txt">{{item.mkmc}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
  styleUrls: ['./ctrcenter_hubeiPt.css'],
})
export class Ctrcenter_hubeiPTComponent implements OnInit, OnDestroy {
  ctrroomHeightstr: string = "0px";
  userinfo: any;
  //所有的模块权限---和【菜单管理】url一一对应（必须同步）----路由配置url，作为参考基准
  allModules: any[] = [{
    url: "sjgzxin.zs",
    hasr: false,
    iconclass: "row1",
    mkmc: "试卷跟踪展示"
  }, {
    url: "sjgzxin.jcsj",
    hasr: false,
    iconclass: "row2",
    mkmc: "跟踪系统管理"
  }, {
    url: "sjgzxin.sbyw",
    hasr: false,
    iconclass: "row3",
    mkmc: "设备运维保障"
  }];
  loginusername: string;
  nowrolemc: string;
  loginuserRoleList: any[] = [];
  nowroleid: string;
  syschildren: any;

  /**
   * 有权限的模块 显示（点亮）
   */
  handModules(): void {
    if (!this.nowroleid) {
      return
    }
    this.commservice.getroleMenus("0", this.nowroleid, (resp) => {
      resp.forEach((item) => {
        const hascode = item.code.toString().trim();
        // 处理模块权限的显示
        this.allModules.forEach((m) => {
          if (hascode == m.url) {
            m.hasr = true;
            m["menuid"] = item.id;
            // m["mkmc"] = item.name;
          }
        });
      });
      this.commservice.log("hasmodule", this.allModules);
    });
  }


  /**
   * url: "",
   hasr: false,
   * @param moduleobj
   */
  gotoModule(moduleobj: any): void {
    this.localstorage.remove("mtmenus");
    this.localstorage.remove("tmenukeyValue");
    const hasrole = moduleobj.hasr;
    const moduleurl = moduleobj.url;
    const moduleid = moduleobj.menuid;
    if (!hasrole) {
      this.commservice.myswal("warning", "该登入用户没有此模块权限", "", 'ts', null);
      return
    }
    this.commservice.getroleMenus(moduleid, this.nowroleid, (resp) => {
      if (resp && resp.length) {
        const topmenus: any[] = [];
        const topmenuskeyvalue: any = {}; // url  --id
        resp.forEach((item) => {
          topmenus.push({
            url: item.code.toString().trim(),
            name: item.name.toString().trim(),
            type: item.type,
            id: item.id
          });
          if (!topmenuskeyvalue[item.code.toString().trim()]) {
            topmenuskeyvalue[item.code.toString().trim()] = item.id;
          }
        });
        const aestr_topmenus = this.commservice.aesString(JSON.stringify(topmenus));
        const aestr_topmenuskeyvalue = this.commservice.aesString(JSON.stringify(topmenuskeyvalue));
        this.localstorage.set("mtmenus", aestr_topmenus);
        this.localstorage.set("tmenukeyValue", aestr_topmenuskeyvalue);
        this.router.navigate(['/' + moduleurl]);
      } else {
        alert("用户没有下级菜单");
      }
    });
  }

  /**
   * 用户详情
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      this.loginusername = info.name ? decodeURIComponent(info.name) : "";
      this.nowrolemc = info.nowrolename ? decodeURIComponent(info.nowrolename) : "";
      this.nowroleid = info.nowroleid;
      this.loginuserRoleList = info.roleInfoList; //code  id  name
      this.handModules();
    });
  }

  /**
   * 选择当前系统使用的角色
   * code
   * id
   * name
   * @param obj
   */
  selectNowRole(obj: any): void {
    const mc = obj.name;
    const id = obj.id;
    const code = obj.code;
    this.nowrolemc = mc;
    this.nowroleid = id;
    this.resetModules();
    this.handModules(); // 更新当前角色的 模块权限
    // 更新掉 用户详情里的角色信息  nowroleid  +  nowrolecode
    const aesuserinfostr = this.localstorage.get('info');
    if (aesuserinfostr) {
      const daesuserifostr = this.commservice.daesString(aesuserinfostr);
      const infoobj = JSON.parse(daesuserifostr);
      infoobj["nowroleid"] = id;
      infoobj["nowrolecode"] = code;
      infoobj["nowrolename"] = decodeURIComponent(mc);
      const infostr = JSON.stringify(infoobj);
      const aessuserinfostr = this.commservice.aesString(infostr);
      this.localstorage.set("info", aessuserinfostr);
    }
  }

  resetModules(): void {
    this.allModules.forEach((obj) => {
      obj.hasr = false
    });
  }

  /**
   * 修改密码
   */
  editePWD(): void {
    // let dom = this.cfr.resolveComponentFactory(DynamicCompEditePwd);
    // this.domRoom.clear();
    // this.domRoom.createComponent(dom);
    // $('#updatapassModal').modal('show');
    this.localstorage.set("ucoreQK", "onlymm");
    this.router.navigate(["/ucore"]);
  }

  /**
   * 返回登入页面
   */
  toLogin(): void {
    sessionStorage.clear();
    this.router.navigate(["login"]);
  }

  /**
   * 使用window 对象的事件
   * @param event
   */
  @HostListener("window:resize", ["$event"])
  onResize(event) {
    this.ctrroomHeightstr = this.commservice.getViewPort().height + "px";
  }

  constructor(private localstorage: LocalStorageService,
              private commservice: CommService,
              private  router: Router) {

  }

  ngOnInit() {
    this.localstorage.remove("mtmenus");
    this.localstorage.remove("tmenukeyValue");
    this.ctrroomHeightstr = this.commservice.getViewPort().height + "px";
    $("#myCarousel").carousel({
      interval: 2000,
      pause: "hover"
    });
    this.commservice.getSysmsg2((resp) => {
      if (resp) {
        const syslogo = 'assets/img/' + resp.syslogonames + '.png';
        $(".mch-leftimg").css({
          "background-image": 'url(' + syslogo + ')'
        });
        this.syschildren = resp.sysChildren;
      }
    });
    this.getuserinfo();
  }

  ngOnDestroy() {

  }

}
